;;;;init-latex.el
;; https://www.gnu.org/software/auctex/index.html

(use-package cdlatex
  ;;https://github.com/cdominik/cdlatex
  :hook ((LaTeX-mode . turn-on-cdlatex) ;with AUCTeX LaTeX mode
         (latex-mode . turn-on-cdlatex)) ;with Emacs latex mode
  :config
  (setq cdlatex-math-symbol-alist
        '((?a ("\\alpha" "\\angle"))
          (?c ("\\circ"))
          ))
  )

;; Here is how to add new math symbols to CDLaTeX's list: In order to put
;; all rightarrow commands onto `>, ``>, ```>, and ````> (i.e. several
;; backquotes followed by >) and all leftarrow commands onto '<, ``<, ```<,
;; and ````<,  you could do this in .emacs:

;;   (setq cdlatex-math-symbol-alist
;; '((?< ("\\leftarrow" "\\Leftarrow" "\\longleftarrow" "\\Longleftarrow"))
;;   (?> ("\\rightarrow" "\\Rightarrow" "\\longrightarrow" "\\Longrightarrow"))
;;    ))

;; To change the prefix key for math accents and font switching, you could
;; do something like

;;   (setq cdlatex-math-modify-prefix [f7])
;; M-x customize-variable [return] cdlatex-math-modify-alist


(use-package tex  ; auctex
  ;; https://github.com/jwiegley/use-package/issues/379
  ;; ELPA users shouldn't use tex-site since the file gets required during package initialization.
  :ensure auctex
  ;; :init
  ;;----------------------------------------------
  ;; the \\' matches the end of the filename
  ;; https://www.emacswiki.org/emacs/AutoModeAlist
  :mode ("\\.tex\\'" . LaTeX-mode)
  :hook ((LaTeX-mode . turn-on-reftex)
         (LaTeX-mode . outline-minor-mode)
         (LaTeX-mode . TeX-fold-mode)
         )
  :config
  ;; XeLaTeX 支持
  (add-hook 'LaTeX-mode-hook
            (lambda()
              (add-to-list 'TeX-command-list '("XeLaTeX" "%`xelatex%(mode)%' %t" TeX-run-TeX nil t))
              (setq TeX-command-default "XeLaTeX")
              ))
  ;; texlive 安装位置, 编译安装时, 应该已有定义
  ;; (setq TeX-tree-roots "c:/texlive/2020/texmf-dist/")
  ;;----------------------------------------------
  ;; 数学符号默认字体为Cambria Math, windows系统自带
  (set-fontset-font "fontset-default" 'symbol
                    "Cambria Math")
  ;;----------------------------------------------
  (setq TeX-save-query nil )
  (setq TeX-show-compilation t)
  ;; 对新文件自动解析(usepackage, bibliograph, newtheorem等信息)
  (setq TeX-parse-self t) ; Enable parse on load.
  (setq TeX-auto-save t) ; Enable parse on save.
  ;; 多文档处理 编译时问询主文件名称
  (setq-default TeX-master nil)
  ;; (setq TeX-engine 'xetex)
  (setq reftex-plug-into-AUCTeX t)
  ;; 正常情况下, preview-gs-command 已有值
  ;; (setq preview-gs-command "c:/texlive/2020/bin/win32/rungs.exe") ;preview latex
  ;;----------------------------------------------
  ;; preview 图片的放大倍数, 有时默认值太小
  (set-default 'preview-scale-function 3.0)
  ;;----------------------------------------------
  ;; PDF正向搜索相关设置
  (setq TeX-PDF-mode t)
  (setq TeX-source-correlate-mode t)
  ;; 对于 xelatex , 需手动添加参数 --synctex=1 , 才能产生PDF和源文件索引synctex.gz
  ;; 可使用 M-! xelatex --synctex=1 filename
  ;; latex(pdflatex) 命令, 是自动添加上述参数
  (setq TeX-source-correlate-method 'synctex)
  (if  *is-windows*
      (setq TeX-view-program-list
            '(("Sumatra PDF" ("\"C:/Program Files (x86)/SumatraPDF/SumatraPDF.exe\" -reuse-instance" (mode-io-correlate " -forward-search %b %n ") " %o")))))
  ;; 下面一行代码复制到Sumatra PDF的option中
  ;; "D:/emacs.26/bin/emacsclientw.exe" -n +%l "%f"
  ;; https://sites.google.com/site/juanjosegarciaripoll/blog/fool-s-guide-to-installing-emacs-and-auctex-in-windows
  ;;   Step 2: Configure SumatraPDF
  ;; Open SumatraPDF and click on the top-left corner menu you have to make two changes:
  ;;     Select "Settings" and "Advanced Options" and ensure that there is a line saying
  ;; EnableTeXEnhancements = true
  ;;     Select "Settings" and then "Options" and enter the following text
  ;; "C:\Program Files\emacs\bin\emacsclientw.exe" -n +%l "%f"
  ;; Make sure the path c:\Program Files\emacs corresponds to the folder where you unzipped your emacs installation.
  (if *is-windows*
      (add-hook 'LaTeX-mode-hook
                (lambda ()
                  (assq-delete-all 'output-pdf TeX-view-program-selection)
                  (add-to-list 'TeX-view-program-selection '(output-pdf "Sumatra PDF")))))
  ;;-----------------------------------------------
  ;; 配置 RefTeX
  ;; https://www.gnu.org/software/auctex/manual/reftex.html#SEC19
  ;;  Adding Magic Words
  (setq reftex-label-alist
        '((nil ?e nil nil nil ("方程" "式"))
          (nil ?s nil nil nil ("第"))
          (nil ?f nil nil nil ("图"))))

  ;; C-c )  reftex-reference 时, 不用再格式选择
  ;; https://tex.stackexchange.com/questions/139824/disabling-the-select-reference-format-menu-in-reftex
  (setq  reftex-ref-macro-prompt nil)
  ;;-----------------------------------------------
  ) ; auctex config end


;;---------------------------------------------------------------------
;; company backends
(use-package company-auctex
  ;; https://github.com/alexeyr/company-auctex/
  ;; :hook((LaTeX-mode . company-auctex-init))
  )

(defun my-latex-company ()
  "latex-mode's company Merged backend"
  (require 'company-auctex)
  (require 'company-my-latex-backend)
  (when (boundp 'company-backends)
    (make-local-variable 'company-backends)
    ;; remove
    ;; (setq company-backends (delete 'company-dabbrev company-backends))
    ;; add
    ;; https://github.com/company-mode/company-mode/issues/407
    (setq company-backends (copy-tree company-backends))
    (setf (car company-backends)
          (append '(company-auctex-bibs
                    company-auctex-labels
                    company-auctex-macros
                    company-auctex-symbols
                    company-auctex-environments
                    company-my-latex-backend)
                  (car company-backends)))
    ;; (add-to-list 'company-backends
    ;;              '(company-auctex-bibs
    ;;                company-auctex-labels
    ;;                company-my-latex-backend
    ;;                company-yasnippet
    ;;                company-dabbrev
    ;;                ))
    ;; (add-to-list 'company-backends
    ;;              '(company-auctex-macros company-auctex-symbols company-auctex-environments))
  ))

(add-hook  'LaTeX-mode-hook 'my-latex-company)
;;---------------------------------------------------------------------


(provide 'init-latex)
